package com.book.controller;

import cn.hutool.captcha.LineCaptcha;
import com.book.entity.Account;
import com.book.service.AccountService;
import com.book.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author SuperYu  2024/6/17
 */

@RestController
@Slf4j
public class LoginController {

    AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    @Resource
    LineCaptcha lineCaptcha;

    @Resource
    HashMap<String,String> map ;

    @PostMapping("/doLogin")
    public JsonResult<Account> login(String username, String password, String code, String codeId,  HttpSession session) {
        log.info("用户名："+username+",密码码："+password+",验证码："+code);
        JsonResult<Account> jsonResult = new JsonResult<>();
        // 先验证码通过，才进行后面的操作：
       // boolean f = lineCaptcha.verify(code);

        // 从缓存中得到codeId匹配的code进行验证
        String mapCode = map.get(codeId);

        if (mapCode != null && mapCode.equalsIgnoreCase(code)) {
            Account account = accountService.findAccountByLogin(username);
            if (account != null) {
                if (account.getPassword().equals(password)) {
                    jsonResult.setStatus(200);
                    jsonResult.setMessage("登录成功!");
                    // 把用户名存入到session里面
                    session.setAttribute("loginName", username);
                } else {
                    jsonResult.setStatus(500);
                    jsonResult.setMessage("对不起,密码有误！");
                }
            } else {
                jsonResult.setStatus(500);
                jsonResult.setMessage("对不起,用户名有误！");
            }
        } else {
            jsonResult.setStatus(500);
            jsonResult.setMessage("验证码有误！");
        }
        return jsonResult;
    }

}
